<template>
  <div>
    <form @submit.prevent="beforeSubmit" method="post" class="theForm">
      <div class="stepsBox">
        <div id="stepOne"><img src="../../assets/images/step-one.png" alt="">
          <div class="iconBgBlue">
            <div class="iconWhite">1</div>
          </div>
          <span>司机信息</span>
        </div>
        <div id="stepTwo"><img src="../../assets/images/step-two-charged.png" alt="">
          <div class="iconBgBlue">
            <div class="iconWhite">2</div>
          </div>
          <span>车辆信息</span>
        </div>
        <div id="stepThree"><img src="../../assets/images/step-three-nocharge.png" alt="">
          <div class="iconBgWhite">
            <div class="iconGray">3</div>
          </div>
          <span>等待审核</span>
        </div>
      </div>
      <div class="theBlock">
        <div class="title">
          车辆信息
        </div>
        <div class="contain">
          <div>
            <span>车牌号</span><input type="text" @blur="carNumCheck" name="carNum" id="carNum" placeholder="请输入车牌号"
              v-model="jsonObj.carNum" :disabled="masked" required />
          </div>
          <div>
            <span>车辆所有人</span><input type="text" @blur="carOwnerCheck" name="carOwner" id="carOwner"
              placeholder="请输入车辆所有人" v-model="jsonObj.carOwner" :disabled="masked" required />
          </div>
          <div>
            <span>品牌</span>
            <select name="carBrand" id="carBrand" v-model="jsonObj.carBrand" :disabled="masked" required>
              <option value="">请选择品牌</option>
              <option v-for="carBrand in brandList" :key="carBrand.id" :value="carBrand.id">{{ carBrand.dataName }}
              </option>
            </select>
          </div>
          <div>
            <span>注册日期</span><input type="date" @blur="registerDateCheck" name="registerDate" id="registerDate"
              v-model="jsonObj.registerDate" :disabled="masked" required />
          </div>
          <div>
            <span>车证有效日期</span><input type="date" @blur="licenseEffectCheck" name="licenseEffect" id="licenseEffect"
              v-model="jsonObj.licenseEffect" :disabled="masked" required />
          </div>
          <div>
            <span>车辆颜色</span><input type="text" name="carColor" id="carColor" placeholder="请输入车辆颜色"
              v-model="jsonObj.carColor" :disabled="masked" required />
          </div>
          <div>
            <span>核载人数</span><input type="text" @blur="peopleNumCheck" name="peopleNum" id="peopleNum"
              placeholder="请输入核载人数" v-model="jsonObj.peopleNum" :disabled="masked" required />
          </div>
          <div>
            <span>下次年检日期</span><input type="date" @blur="checkDateCheck" name="checkDate" id="checkDate"
              v-model="jsonObj.checkDate" :disabled="masked" required />
          </div>
          <div>
            <span>燃料类型</span>
            <select name="fuelType" id="fuelType" v-model="jsonObj.fuelType" :disabled="masked" required>
              <option value="">请选择燃料类型</option>
              <option v-for="fuelType in fuelTypes" :key="fuelType.key">{{ fuelType.value }}</option>
            </select>
          </div>
        </div>
      </div>
      <div class="theBlock">
        <div class="title">
          证件信息
        </div>
        <div class="imgContain">
          <FileUpload keyName="travelLicence" @childMessage="handleChildMessage" needed="true"><span
              class="point">*</span>行驶证
          </FileUpload>
          <FileUpload keyName="carPhoto" @childMessage="handleChildMessage" needed="false">车证<span
              class="noPoint">（非必填）</span>
          </FileUpload>
        </div>
      </div>
      <div class="theBlock">
        <div class="contain">
          <div>
            <span>所在区域</span><input type="text" readonly name="registePlace" id="registePlace" v-model="area">
          </div>
        </div>
      </div>
      <input type="submit" value="提交审核">
    </form>
  </div>
</template>
<script>
import FileUpload from '../FileUpload.vue';
import axios from 'axios';

export default {
  name: 'VehicleData',
  components: {
    FileUpload,
  },
  mounted() {
    this.getBrandsList();   /* 获取车辆品牌 */

    const date = new Date();    /* 今日日期 */
    const y = date.getFullYear();
    const m = date.getMonth() + 1;
    const d = date.getDate();
    if (m >= 9) {
      this.today = Number(y + '' + m + '' + d)
    } else {
      this.today = Number(y + '' + 0 + '' + m + '' + d)
    }
  },
  props: {
    masked: Boolean
  },
  data() {
    return {
      today: Number,
      fuelTypes: [
        { key: '汽油', value: '汽油' },
        { key: '柴油', value: '柴油' },
        { key: '电动', value: '电动' },
        { key: '混动', value: '混动' },
      ],
      fileReceived: File,
      formData: new FormData(),
      jsonObj: {
        carNum: '',
        carOwner: '',
        carBrand: '',
        registerDate: '',
        licenseEffect: '',
        carColor: '',
        peopleNum: '',
        checkDate: '',
        fuelType: '',
      },
      area: '',
      brandList: [],
    };
  },
  methods: {
    //获得车辆品牌列表
    getBrandsList() {
      axios.get('/api/carsBrand/list').then(res => {
        this.brandList = res.data.data;
        this.sortBrandList();
      }).catch(r => {
        this.$emit('dialog-trigger', r);
        console.log(r);
      })
    },
    //子品牌一并拆进列表
    sortBrandList() {
      for (let i = 0; this.brandList.length > i; i++) {
        if (this.brandList[i].brandList.length != 0) {
          for (let item of this.brandList[i].brandList) {
            this.brandList.push(item);
          }
        }
      }
    },
    //图片放进数组
    handleChildMessage(msg) {
      this.fileReceived = msg.img;
      this.formData.append(msg.key, this.fileReceived);
    },
    beforeSubmit() {
      //formData转换为json
      this.formData.forEach((value, key) => { this.jsonObj[key] = value })
      //组件获得数据加入store
      this.$store.commit('addVehicleData', this.jsonObj);
      //获取store中的数据并上传
      const theUploadOne = this.$store.state.theUpload;
      axios.post('/api/driver/registe', theUploadOne).then(res => {
        if (res.data.code == 200) {
          this.$router.push('/success');
        } else {
          this.$emit('dialog-trigger', res.data.msg);  /* 这里告诉父组件该车辆注册已超过三人，弹出dialog */
        }
      }).catch(r => {
        const text = '网络错误' + r;
        window.alert(text);
      })
    },
    carOwnerCheck() {
      let reg = /[\u4e00-\u9fff·]+/g
      if (this.jsonObj.carOwner === '') {
        return
      } else if (!reg.test(this.jsonObj.carOwner)) {
        this.jsonObj.carOwner = '';
        this.$emit('dialog-trigger', '姓名格式不正确');
      }
    },
    carNumCheck() {
      //普通车牌一共七位
      let c_reg = /^[京津冀晋蒙辽吉黑沪苏浙皖闽赣鲁豫鄂湘粤桂琼川贵云渝藏陕甘青宁新]{1}[ABCDEFGHJKLMNOPQRSTUVWXY]{1}[0-9A-Z]{5}$/ui;
      // 新能源八位 新能源小型车
      let xs_reg = /^[京津冀晋蒙辽吉黑沪苏浙皖闽赣鲁豫鄂湘粤桂琼川贵云渝藏陕甘青宁新]{1}[ABCDEFGHJKLMNPQRSTUVWXY]{1}[DF]{1}[1-9ABCDEFGHJKLMNPQRSTUVWXYZ]{1}[0-9]{4}$/ui;
      // 新能源大型车
      let xb_reg = /^[京津冀晋蒙辽吉黑沪苏浙皖闽赣鲁豫鄂湘粤桂琼川贵云渝藏陕甘青宁新]{1}[ABCDEFGHJKLMNPQRSTUVWXY]{1}[0-9]{5}[DF]{1}$/ui;
      if (this.jsonObj.carNum === '') return;
      if (this.jsonObj.carNum.length === 7) {
        if (!c_reg.test(this.jsonObj.carNum)) {
          this.jsonObj.carNum = '';
          this.$emit('dialog-trigger', '车牌号格式有误，请重新输入')
        }
      } else if (this.jsonObj.carNum.length === 8) {
        if (!xs_reg.test(this.jsonObj.carNum) && !xb_reg.test(this.jsonObj.carNum)) {
          this.jsonObj.carNum = '';
          this.$emit('dialog-trigger', '车牌号格式有误，请重新输入')
        }
      } else {
        this.jsonObj.carNum = '';
        this.$emit('dialog-trigger', '车牌号格式有误，请重新输入')
      }
    },
    registerDateCheck() {
      let time = Number(this.jsonObj.registerDate.replace(/-/g, ''))
      if (this.jsonObj.registerDate === '') return;
      if (time > this.today) {
        this.jsonObj.registerDate = '';
        this.$emit('dialog-trigger', '注册日期不可超出今日');
      }
    },
    licenseEffectCheck() {
      let time = Number(this.jsonObj.licenseEffect.replace(/-/g, ''))
      if (this.jsonObj.licenseEffect === '') return;
      if (time < this.today) {
        this.jsonObj.licenseEffect = '';
        this.$emit('dialog-trigger', '车证已过有效日期');
      }
    },
    peopleNumCheck() {
      let reg = /[0-9]/g
      if (this.jsonObj.peopleNum === '') {
        return
      } else if (!reg.test(this.jsonObj.peopleNum)) {
        this.jsonObj.peopleNum = '';
        this.$emit('dialog-trigger', '核载人数格式不正确');
      }
    },
    checkDateCheck() {
      let time = Number(this.jsonObj.checkDate.replace(/-/g, ''))
      if (this.jsonObj.checkDate === '') return;
      if (time < this.today) {
        this.jsonObj.checkDate = '';
        this.$emit('dialog-trigger', '下次年检日期不可在今日之前');
      }
    },
  }
};
</script>

<style scoped>
@import "../../assets/css/style.css";

#stepOne,
#stepTwo {
  color: #ffffff;
}
</style>